package ltd.newbee.mall.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.entity.AdminLogin;
import ltd.newbee.mall.entity.AdminUser;
import ltd.newbee.mall.event.LoginEvent;
import ltd.newbee.mall.service.AdminLoginService;
import ltd.newbee.mall.service.AdminUserService;
import ltd.newbee.mall.util.AddressUtils;
import ltd.newbee.mall.util.IpUtils;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 事件监听
 */
@Slf4j
@AllArgsConstructor
@Component
public class LoginListener {

    private final AdminLoginService adminLoginService;

    private final AdminUserService adminUserService;

    /***
     * 登录事件
     * @param event
     */
    @Async
    @Order
    @EventListener(LoginEvent.class)
    public void onLoginEvent(LoginEvent<HttpServletRequest> event) {
        String token = (String) event.getSource();
        log.info("登录日志 onLoginEvent --> token = {}", token);
        AdminUser user = adminUserService.selectByToken(token);
        AdminLogin login = new AdminLogin();
        login.setLoginTime(DateUtil.date().toSqlDate());
        HttpServletRequest request = event.getPayload();
        String ip = IpUtils.getIpAddr(request);
        login.setIp(ip);
        login.setAddress(AddressUtils.getRealAddressByIP(ip));
        login.setNickName(user.getNickName());
        login.setUserId(user.getAdminUserId());
        String ua = request.getHeader("user-agent");
        UserAgent userAgent = UserAgentUtil.parse(ua);
        login.setBrowser(userAgent.getBrowser().getName());
        login.setOs(userAgent.getOs().getName());
        login.setUa(ua);
        adminLoginService.save(login);
    }

}
